import React, { ReactElement, useCallback, useReducer, useEffect } from "react";
import TdInput from "../Components/TodoListCom/Input/index";
import TdList from "../Components/TodoListCom/List/index";
import { todoReducer } from "../Components/reducer";
import { ACTION_TYPE, IState, ITodo } from "../Components/TodoListCom/typings";
// const initialState: IState = {
//   todoList: []
// }
function init(intiTodoList: ITodo[]): IState {
  return {
    todoList: [],
  };
}
// 父级统一调用useCallback, useState, useEffect等hook
const TodoList: React.FC = (): ReactElement => {
  // 该处todoList属性也要归属于ITodo，并初始化为一个空数组
  // const [todoList, setTodoList] = useState<ITodo[]>([]);

  const [state, dispatch] = useReducer(todoReducer, [], init);
  // 监听
  useEffect(() => {
    const todoList = JSON.parse(localStorage.getItem("todoList") || "[]");
    dispatch({
      type: ACTION_TYPE.INIT_TODOLIST,
      payload: todoList,
    });
  }, []);

  // 传入事件，该事件是执行useState的方法，使用扩展运算符，
  // 提交一个对象，此处应用useCallbac包裹，这是一种规范。
  const addTodo = useCallback((todo: ITodo) => {
    // setTodoList((todoList) => [...todoList, todo]);
    dispatch({
      type: ACTION_TYPE.ADD_TODO,
      payload: todo,
    });
  }, []);
  const removeTodo = useCallback((id: number) => {
    dispatch({
      type: ACTION_TYPE.REMOVE_TODO,
      payload: id,
    });
  }, []);
  const toggledTodo = useCallback((id: number) => {
    dispatch({
      type: ACTION_TYPE.TOGGLE_TODO,
      payload: id,
    });
  }, []);
  useEffect(() => {
    localStorage.setItem("todoList", JSON.stringify(state.todoList));
  }, [state.todoList]);
  return (
    <div>
      <TdInput addTodo={addTodo} todoList={state.todoList} />
      <TdList
        todoList={state.todoList}
        removeTodo={removeTodo}
        toggledTodo={toggledTodo}
      />
    </div>
  );
};
export default TodoList;
